<?php


class CMyActiveForm extends CActiveForm
{
	private static $indexWidget=0;
	
	public static $builtInTypeEditors=array(
		'date'=>'datetime',
		'datetime'=>'datetime',
//		'time'=>'datetimeField',
		'string'=>'text',
		'boolean'=>'checkBox',
		'text'=>'memo',
	);	 
	
	/**
	 * @var string the template used to render a single attribute. Defaults to a table row.
	 * These tokens are recognized: "{class}", "{label}" and "{value}". They will be replaced
	 * with the CSS class name for the item, the label and the attribute value, respectively.
	 * @see itemCssClass
	 */
	public $itemTemplate="<div class=\"row {class}\"><div class=\"label\">{label}</div><div class=\"value\">{value}</div>{error}</div>\n";	
	/**
	 * @var DirModel the data model whose details are to be displayed.
	 */
	public $model;

	/**
	 * @var array the HTML options used for {@link tagName}
	 */
	public $htmlOptions=array('class'=>'detail-edit');
	/**
	 * @var string the text to be displayed when an attribute value is null. Defaults to "Not set".
	 */
	public $nullDisplay;
	/**
	 * @var array the CSS class names for the items displaying attribute values. If multiple CSS class names are given,
	 * they will be assigned to the items sequentially and repeatedly.
	 * Defaults to <code>array('odd', 'even')</code>.
	 */
	public $itemCssClass=array('odd','even');
	
	public $showSummaryError=true;

//	public $enableAjaxValidation=true;
	
	public function createEditor($editor,$attribute,$htmlOptions)
	{	
		$temp=array();
		if(isset($htmlOptions['label']))
		{		
			$temp['{label}']=$htmlOptions['label'];
			unset($htmlOptions['label']);
		}
		else
			$temp['{label}']=$this->model->getAttributeLabel($attribute);		
		if(isset($htmlOptions['class']))
		{
			$temp['{class}']=$htmlOptions['class'];
			unset($htmlOptions['class']);
		}
		else
			$temp['{class}']='';
		if(isset($htmlOptions['template']))
		{
			$template=$htmlOptions['template'];
			unset($htmlOptions['template']);
		}
		else
			$template=$this->itemTemplate;
						
		if(method_exists($this->model,$editor.'Field'))
			$temp['{value}']=$this->model->{$editor.'Field'}($attribute,$htmlOptions);
		elseif(method_exists($this,$editor.'Field'))
			$temp['{value}']=$this->{$editor.'Field'}($this->model,$attribute,$htmlOptions);		
		else
			$temp['{value}']='';
		
		$temp['{error}']=$this->error($this->model,$attribute);		
		echo strtr($template,$temp);	
	}
	
	public function getAttributeEditor($attribute)
	{
		if ($this->model instanceof CActiveRecord)
		{
			$column=$this->model->getMetaData()->columns[$attribute];
			if (($column->isPrimaryKey)&&($this->model->tableSchema->sequenceName!==null))
				return null;
			if(isset($column)&& isset(self::$builtInTypeEditors[$column->dbType]))
				return self::$builtInTypeEditors[$column->dbType];
		}
		return 'text';
	}
	
	/**
	 * Initializes the widget.
	 * This renders the form open tag.
	 */
	public function init()
	{
		if($this->model===null)
			throw new CException(Yii::t('zii','Please specify the "model" property.'));
		$this->setId($this->model->getHtmlId());
		parent::init();
	}
	
	/**
	 * Runs the widget.
	 * This registers the necessary javascript code and renders the form close tag.
	 */
	public function run()
	{
		echo '<div class="form">';
		
		echo '<p class="note">Fields with <span class="required">*</span> are required.</p>';
		
		if ($this->showSummaryError)
			echo $this->errorSummary($this->model);
		
		$attributes=($this->model->updateFields===array())?array_keys($this->model->attributes):$this->model->updateFields;
			
		$n=is_array($this->itemCssClass) ? count($this->itemCssClass) : 0;
		foreach ($attributes as $i=>$attribute)
		{
			if(is_string($attribute))
			{
				$editor=$this->getAttributeEditor($attribute);
				$htmlOptions=array();
				$attrName=$attribute;
			}
			elseif(is_array($attribute))
			{
				$htmlOptions=$attribute;
				if (isset($htmlOptions['name']))
				{
					$attrName=$htmlOptions['name'];
					unset($htmlOptions['name']);
					if (isset($htmlOptions['editor']))
					{
						$editor=$htmlOptions['editor'];
						unset($htmlOptions['editor']);
					}
					else
						$editor=$this->getAttributeEditor($attrName);
				}				
				else
					continue;
			}else
				continue;
			$editorParams['class']=$n ? $this->itemCssClass[$i%$n] : '';
			if (!empty($editor))
				$this->createEditor($editor,$attrName,$htmlOptions);
		}
		
		echo CHtml::hiddenField('ajax',$this->model->getHtmlId());
//		echo CHtml::hiddenField(Yii::app()->request->csrfTokenName,Yii::app()->request->csrfToken);
		
		echo CHtml::submitButton($this->model->isNewRecord ? 'Создать' : 'Сохранить');
		
		parent::run();
		
		echo '</div><!-- form -->';
	}
	
	/**
	 * Renders a text field for a model attribute.
	 * This method is a wrapper of {@link CJuiDatePicker}.
	 * Please check {@link CJuiDatePicker} for detailed information
	 * about the parameters for this method.
	 */
	public function datetimeField($model,$attribute,$htmlOptions=array())
	{
		return $this->widget('zii.widgets.jui.CJuiDatePicker',array(
				'model'=>$model,
				'attribute'=>$attribute,
				'htmlOptions'=>$htmlOptions,			 
		),true);
	}

	/**
	 * Renders a text field for a model attribute.
	 * This method is a wrapper of {@link CJuiDatePicker}.
	 * Please check {@link CJuiDatePicker} for detailed information
	 * about the parameters for this method.
	 */
	public function memoField($model,$attribute,$htmlOptions=array())
	{
		return CHtml::activeTextArea($model,$attribute,$htmlOptions);
	}
	
	public function checkBoxField($model,$attribute,$htmlOptions=array())	
	{	
		return CHtml::activeCheckBox($model,$attribute,$htmlOptions);  
	}

	public function checkBoxListField($model,$attribute,$htmlOptions=array())	
	{
	if (isset($htmlOptions['data']))
		{
			$data=$htmlOptions['data'];
			unset($htmlOptions['data']);
		}	
		return CHtml::activeCheckBoxList($model,$attribute,$data,$htmlOptions);  
	}

	public function checkBoxGroupListField($model,$attribute,$htmlOptions=array())	
	{ 
		if (isset($htmlOptions['data']))
		{
			$data=$htmlOptions['data'];
			unset($htmlOptions['data']);
		}			
		return CMyHtml::activeCheckBoxGroupList($model,$attribute,$data,$htmlOptions);  
	}	
	
	public function textField($model,$attribute,$htmlOptions=array())
	{
		return CHtml::activeTextField($model,$attribute,$htmlOptions);
	}

	public function hiddedField($model,$attribute,$htmlOptions=array())
	{
		return CHtml::activeHiddenField($model,$attribute,$htmlOptions);
	}

	public function labelField($model,$attribute,$htmlOptions=array())
	{
		return CHtml::activeLabelEx($model,$attribute,$htmlOptions);
	}	
	
	public function dropDownField($model,$attribute,$htmlOptions=array())
	{
		if (isset($htmlOptions['data']))
		{
			$data=$htmlOptions['data'];
			unset($htmlOptions['data']);
		}
		return CHtml::activeDropDownList($model,$attribute,$data,$htmlOptions);
	}
	
	public function ajaxDropDownField($model,$attribute,$htmlOptions=array())
	{
		if (isset($htmlOptions['data']))
		{
			$data=$htmlOptions['data'];
			unset($htmlOptions['data']);
		}
		if (!isset($htmlOptions['replace']))
			$htmlOptions['replace']='#'.$this->id;
		$htmlOptions['ajax']=array(
				'success'=>'js:function(html){jQuery("'.$htmlOptions['replace'].'").replaceWith($(html).find("'.$htmlOptions['replace'].'"));}',
			//	'data'=>array(get_class($model)=>array($attribute=>'js:$("#'.CHtml::activeId($model,$attribute).'").val()')),
				'type'=>'POST',
		);
		unset($htmlOptions['replace']);
		return CHtml::activeDropDownList($model,$attribute,$data,$htmlOptions);
	}
	
}